using System.IO;
using MLSharp.Utilities;

namespace MLSharp.Cpn
{
	/// <summary>
	/// A helper class that writes data sets to files for consumption by CPN.
	/// </summary>
	internal static class CpnDataWriter
	{
		/// <summary>
		/// Writes training data to a CPN table file.
		/// </summary>
		/// <param name="trainingData"></param>
		/// <param name="tableName"></param>
		public static void WriteTrainingData(IDataSet trainingData, string tableName)
		{
			trainingData.AssertNumeric();

			using (StreamWriter writer = File.CreateText(tableName))
			{
				foreach (Instance instance in trainingData.Instances)
				{
					for (int i = 0; i < instance.Values.Length; i++)
					{
						double value = instance.Values[i];

						writer.Write("{0}\t", value.FormatForWriting());
					}

					writer.WriteLine();
				}
			}
		}

		/// <summary>
		/// Writes data for testing to the specified table file.
		/// </summary>
		/// <param name="dataSet"></param>
		/// <param name="inputTableName"></param>
		public static void WriteTestingData(IDataSet dataSet, string inputTableName)
		{
			dataSet.AssertNumeric();

			using (StreamWriter writer = File.CreateText(inputTableName))
			{
				foreach (Instance instance in dataSet.Instances)
				{
					for (int i = 0; i < instance.Values.Length; i++)
					{
						//Don't write the target value
						if (i == dataSet.TargetAttributeIndex)
						{
							continue;
						}

						double value = instance.Values[i];

						writer.Write("{0}\t", value.FormatForWriting());
					}

					writer.WriteLine();
				}
			}
		}
	}
}
